package org.example.communication_room.exception;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.example.communication_room.utils.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.sql.SQLException;

// 全局异常处理
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 处理请求方法不支持的异常
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<ApiResponse<Object>> handleMethodNotSupported(HttpRequestMethodNotSupportedException e) {
        logger.error("不支持当前请求方法: {}", e.getMethod(), e);
        return new ResponseEntity<>(
                ApiResponse.error(HttpStatus.METHOD_NOT_ALLOWED.value(), "不支持当前请求方法: " + e.getMethod()),
                HttpStatus.METHOD_NOT_ALLOWED);
    }

    // 处理所有未被上面处理的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<Object>> handleGlobalException(Exception e) {
        logger.error("服务器错误", e);
        return new ResponseEntity<>(
                ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器错误: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 处理非法参数异常
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ApiResponse<Object>> handleIllegalArgumentException(IllegalArgumentException ex) {
        logger.warn("非法参数：{}", ex.getMessage(), ex);
        return ResponseEntity.badRequest().body(
                ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "非法参数: " + ex.getMessage()));
    }

    // 特定的数据库异常处理
    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity<ApiResponse<Object>> handleDataIntegrityViolation(DataIntegrityViolationException ex) {
        logger.error("数据库操作异常", ex);
        return ResponseEntity.status(HttpStatus.CONFLICT).body(
                ApiResponse.error(HttpStatus.CONFLICT.value(), "数据操作错误: " + ex.getRootCause().getMessage()));
    }
//    处理Token过期异常
    @ExceptionHandler(TokenExpiredException.class)
    public ResponseEntity<ApiResponse<String>> handleTokenExpiredException(TokenExpiredException ex) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.error(401, "Session expired, please log in again."));
    }
    // 处理数据库连接异常
    @ExceptionHandler(SQLException.class)
    public ResponseEntity<ApiResponse<Object>> handleSQLException(SQLException ex) {
        logger.error("数据库连接错误", ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
                ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "数据库连接错误: " + ex.getMessage()));
    }
//    处理JWT验证失败
    @ExceptionHandler(JWTVerificationException.class)
    public ResponseEntity<ApiResponse<String>> handleJWTVerificationException(JWTVerificationException ex) {
        if (ex instanceof TokenExpiredException) {
            return handleTokenExpiredException((TokenExpiredException) ex);
        } else {
            logger.error("JWT verification failed", ex);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
                    ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "Invalid token: " + ex.getMessage())
            );
        }
    }

}
